import axios from "axios";
import router from "@/router";

axios.interceptors.request.use(
    (config) => {
        const token = localStorage.token;
        config.headers.Authorization = token;
        return config;
    },
    (err) => Promise.reject(err)
);

axios.interceptors.response.use(
    (res) => {
        return res;
    },
    (err) => {
        if (err && err.response && err.response.status) {
            switch (err.response.status) {
                case 401:
                    err.message = "身份认证过期";
                    alert("身份认证过期，请重新登录");
                    router.push("/login");
                    break;
                case 404:
                    err.message = "资源找不到";
                    break;
                case 500:
                    err.message = "服务器出错";
                    break;
                default:
                    err.message = "服务器出错";
            }
        } else {
            err.message = "服务器出错";
        }
        return Promise.reject(err.message);
    }
);